<script setup>
	import { computed, nextTick, onMounted, onUnmounted, ref, toRaw, watch } from 'vue'
	import { onShow, onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"
	import { useCartStore } from '@/store/cart'
	import { useUserStore } from '@/store/userInfo'
	import CustomHeadBar from '@/components/custom-head-bar/custom-head-bar.vue'
	import { useShopStore } from '@/store/shop'
	// 响应式数据
	const dataList = ref( [ ] )
	// 用户store
	const userStore = useUserStore( )
	// 购物车store
	const cartStore = useCartStore( )
	// 商店store
	const shopStore = useShopStore( )
	const shopApi = uniCloud.importObject( 'shop', { customUI: true } )
	const shopInfoGet = async ( ) => {
		const res = await shopApi.getShopInfo( )

		let params = {
			shop_name: res.data.shop_name,
			shop_avatar: res.data.shop_avatar,
			shop_desc: res.data.shop_desc,
			code: res.data.shop_code
		}

		shopStore.setShopInfo( params )
	}

	const customHeadBar = ref( null )

	// 链表查询
	const db = uniCloud.databaseForJQL( )
	const getAllData = ( ) => {
		const product = db.collection( 'productList' )
			.field( '_id,name,cover_pic,buy_price,original_price,discount,sku,cate_id' )
			.getTemp( )
		const cate = db.collection( 'cate' )
			.field( '_id,cate_name' )
			.getTemp( )

		db.collection( 'cate', 'productList' )
			.get( )
			.then( res => {
				dataList.value = res.data
				console.log( dataList.value )
			} )
			.catch( err => {
				console.error( '联表查询失败:', err )
				uni.showToast( {
					title: '获取数据失败',
					icon: 'none'
				} )
			} )
	}
	// 高亮时的下标
	const activeIndex = ref( 0 )
	// 绑定scroll-view的scrollTop
	const rightScrollTopValue = ref( 0 )
	const leftScrollTopValue = ref( 0 )
	const rightScrollTop = ref( [ ] )
	const leftScrollTop = ref( [ ] )
	const headHeight = ref( null )

	// 获取头部组件的高度
	const getHead = ( ) => {
		const selectorQuery = uni.createSelectorQuery( )
		selectorQuery.selectAll( '.content' ).boundingClientRect( ( rect ) => {
			headHeight.value = rect[ 0 ].top
		} ).exec( )
	}

	// 获取滚动位置
	const getScroll = ( ) => {
		const selectorQuery = uni.createSelectorQuery( )
		selectorQuery.selectAll( '.left-box' ).boundingClientRect( rus => {
			leftScrollTop.value = rus.map( item => item.top - headHeight.value )
		} ).exec( )

		selectorQuery.selectAll( '.productList' ).boundingClientRect( rus => {
			rightScrollTop.value = rus.map( item => item.top - headHeight.value )
		} ).exec( )
	}

	// 商品响应数据
	const proDataList = ref( [ ] )

	// 步进器改变回调
	const handlerChangeNum = ( e ) => {
		console.log( e, '筛选前' )
		// 商品数量为0 减少 反之增加
		if ( e.num === 0 ) {
			proDataList.value = proDataList.value.filter( item => item.pro_id !== e.pro_id )
		} else {
			const index = proDataList.value.findIndex( item => item.pro_id === e.pro_id )
			if ( index !== -1 ) {
				proDataList.value[ index ].num = e.num
			} else {
				proDataList.value.push( e )
				console.log( proDataList.value, '没有规格' )
			}
		}

		// 选好了
		showFooter( )
	}

	// 定义一个变量来存储定时器 ID
	let scrollTimer = null

	// 合计件数
	const totalCount = computed( ( ) => {
		return proDataList.value.reduce( ( sum, item ) => sum + item.num, 0 )
	} )

	// 总价格
	const totalPrice = computed( ( ) => {
		return proDataList.value.reduce( ( sum, item ) => sum + ( item.num * item.buy_price ), 0 )
	} )

	// 控制购物车时的开关
	const showCart = ref( false )
	const showFooter = ( ) => {
		showCart.value = proDataList.value.length > 0
	}

	// 添加商品到购物车--选好了
	const addCart = ( ) => {
		if ( userStore.userInfo.uid ) {
			cartStore.addToCart( proDataList.value )
			setTimeout( ( ) => {
				uni.navigateTo( {
					url: '/pages/cart/cart2'
				} )
			}, 500 )
		} else {
			uni.showModal( {
				title: '提示',
				content: '请先登录',
				confirmText: "登录",
				success( res ) {
					if ( res.confirm ) {
						uni.navigateTo( {
							url: "/pages/login/login"
						} )
					}
				}
			} )
		}
	}

	// 添加一个标记，用于判断是否是点击触发的滚动
	const isClickScroll = ref( false )

	// 点击处理函数
	const hanlderList = ( index ) => {
		isClickScroll.value = true
		activeIndex.value = index
		rightScrollTopValue.value = rightScrollTop.value[ index ]
		leftScrollTopValue.value = leftScrollTop.value[ index ]

		// 等待滚动动画完成后重置标记
		setTimeout( ( ) => {
			isClickScroll.value = false
		}, 500 )
	}

	// 修改滚动处理函数
	const handleRightScroll = ( e ) => {
		// 如果是点击触发的滚动，不处理高亮更新
		if ( isClickScroll.value ) return

		const scrollTop = e.detail.scrollTop
		const currentIndex = rightScrollTop.value.findIndex( ( top, index ) => scrollTop >= top &&
			scrollTop < ( rightScrollTop.value[ index + 1 ] || Infinity ) )

		if ( currentIndex !== -1 && currentIndex !== activeIndex.value ) {
			activeIndex.value = currentIndex
			// 同步左侧滚动
			leftScrollTopValue.value = leftScrollTop.value[ currentIndex ]
		}
	}

	// 监听数据变化，重新获取滚动位置
	watch( ( ) => dataList.value, ( ) => {
		nextTick( ( ) => {
			getHead( )
			setTimeout( ( ) => {
				getScroll( )
			}, 100 )
		} )
	} )

	onMounted( ( ) => {
		console.log( '组件挂载完成' )
		shopInfoGet( )
	} )

	// 页面显示时调用 getAllData，刷新数据
	onShow( ( ) => {
		getAllData( )
		// 如果是从购物车返回且需要刷新
		if ( cartStore.needRefresh ) {
			console.log( '从购物车回来' )
			proDataList.value = [ ]
			uni.reLaunch( {
				url: "/pages/index/index"
			} )
			// 使用 setTimeout 延迟执行刷新
			cartStore.setNeedRefresh( false )
		} else if ( !dataList.value.length ) {
			// 保持原有的加载判断
			getAllData( )
		}
		// 修改调用方式
		customHeadBar.value?.refresh( )
	} )
	// 客服二维码弹窗
	const popup = ref( null )
	// 头部组件传回的客服事件
	const handlerCode = ( ) => {
		popup.value.open( )
	}

	// 保存图片
	const saveImage = ( ) => {
		uni.showLoading( {
			title: '保存中...'
		} )

		uni.downloadFile( {
			url: shopStore.shopInfo.code,
			success: ( res ) => {
				if ( res.statusCode === 200 ) {
					uni.saveImageToPhotosAlbum( {
						filePath: res.tempFilePath,
						success: ( ) => {
							uni.showToast( {
								title: '保存成功',
								icon: 'success'
							} )
						},
						fail: ( ) => {
							uni.showToast( {
								title: '保存失败',
								icon: 'none'
							} )
						}
					} )
				}
			},
			fail: ( ) => {
				uni.showToast( {
					title: '下载失败',
					icon: 'none'
				} )
			},
			complete: ( ) => {
				uni.hideLoading( )
			}
		} )
	}

	// 商品详情页
	const productDetail = ( pro_id ) => {
		console.log( '我是商品id', pro_id )
		uni.navigateTo( {
			url: `/pages/productDetail/productDetail?proId=${pro_id}`
		} )
	}

	// 配置分享
	onShareAppMessage( ( ) => {
		return {
			title: shopStore.shopInfo.shop_name || '小圆星店',
			path: '/pages/index/index',
			imageUrl: shopStore.shopInfo.shop_avatar
		}
	} )

	// 开启分享到朋友圈
	// #ifdef MP-WEIXIN
	onShareTimeline( ( ) => {
		return {
			title: shopStore.shopInfo.shop_name || '小圆星店',
			query: '',
			imageUrl: shopStore.shopInfo.shop_avatar
		}
	} )
	// #endif
</script>


<template>
	<up-loading-page :loading="false" loading-text="loading..."></up-loading-page>
	<view class="home">
		<!-- 自定义头部 -->
		<custom-head-bar ref="customHeadBar" @contractCode="handlerCode"></custom-head-bar>

		<!-- 产品内容 -->
		<view class="content">
			<!-- 左侧TAB -->
			<view class="tab-left">
				<scroll-view :scroll-y="true" :scroll-top="leftScrollTopValue">
					<!-- 分类 -->
					<view class="left-box" v-for="(item, index) in dataList"
						:class="{ active: activeIndex === index }" :key="index" @tap="hanlderList(index)">
						<!-- 浮标 -->
						<view class="float" v-if="activeIndex === index"></view>
						<!-- 未激活的占位 -->
						<view class="float" v-else style="opacity: 0;"></view>
						<view class="cateText">{{ item.cate_name }}</view>
					</view>
				</scroll-view>
			</view>

			<!-- 右侧垂直内容 -->
			<view class="right">
				<scroll-view class="scroll" scroll-y="true" :scroll-top="rightScrollTopValue"
					@scroll="handleRightScroll" :scroll-with-animation="true">
					<view class="productList" v-for="(item, index) in dataList" :key="index">
						<up-sticky :z-index="2">
							<view class="name">
								{{item.cate_name}}
							</view>
						</up-sticky>
						<!-- 商品 -->
						<view class="pro" v-for="(p, pIndex) in item._id.productList" :key="p._id"
							@tap="productDetail(p._id)">
							<view class="left">
								<image :src="p.cover_pic" mode="aspectFill"></image>
							</view>
							<view class="right">
								<!-- 名字 -->
								<view class="pro-name">
									{{p.name}}
								</view>
								<!-- 价格 -->
								<view class="price">
									<up-text style="width: fit-content;flex: none;" color="#ed544f" mode="price"
										size="14" :text="p.buy_price"></up-text>
									<up-text style="width: fit-content;" class="original-price" mode="price" size="12"
										:text="p.original_price" color="#ababab" decoration="line-through"></up-text>
								</view>
								<!-- 折扣和步进器 -->
								<view class="add-cart">
									<!-- 折扣 -->
									<view class="discount">
										{{p.discount}}折
									</view>
									<!-- 步进器 -->
									<number-box @changeNum="handlerChangeNum" :id="p._id" :name="p.name"
										:cover_pic="p.cover_pic" :buy_price="p.buy_price"
										:original_price="p.original_price" :sku="p.sku"></number-box>
									<!-- sku -->
									<!-- 					<view class="sku" v-else @tap="handelSku(p)">
										选规格
									</view> -->
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 规格面板 -->
		<!-- 		<view class="skuMenu" v-if="showSkuMenu">
			<view class="skuItem" v-for="(item,index) in proDataList[0].sku" :key="index">
				{{item}}
			</view>
			<view class="submit">
				确定
			</view>
		</view> -->
		<!-- 底部合计 -->
		<view class="footer" v-if="showCart">
			<!-- 选好了 -->
			<view class="footer-left">
				<!-- 购物车 -->
				<view class="cartIcon">
					<up-badge type="error" :absolute="true" :offset="[-6,-8]" max="99"
						:value="totalCount"></up-badge>
					<up-icon name="shopping-cart" color="#ed544f" size="26"></up-icon>
				</view>
				<view class="total">
					<up-text size="14" text="合计:"></up-text>
					<up-text mode="price" size="14" :text="totalPrice" color="#ed544f"></up-text>
				</view>
			</view>
			<view class="ready">
				<view class="btn" @tap="addCart">
					选好了
				</view>
			</view>
		</view>
		<!-- 长按保存专享客服 -->
		<uni-popup class="popup" ref="popup" type="center">
			<view class="popup-content">
				<view class="codePic">
					<image :src="shopStore.shopInfo.code" mode="aspectFill" show-menu-by-longpress
						@longpress="saveImage"></image>
				</view>
				<view class="sava">
					<view class="btn" @longpress="saveImage">长按保存</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
	.home {
		display: flex;
		flex-direction: column;

		/*主体内容*/
		.content {
			display: flex;
			justify-content: space-between;
			width: 100%;
			height: calc(100vh - 400rpx);
			background-color: #f8f8f8;
			font-size: 28rpx;

			/*左边tab*/
			.tab-left {
				width: 210rpx;
				height: 100%;
				border-right: 1px solid $line-color-aux;

				.scroll-view-left {
					height: 100%;
				}

				.left-box {
					display: flex;
					align-items: center;
					padding: 16rpx;
					color: $text-font-color-3;

					.float {
						margin-right: 8rpx;
						width: 8rpx;
						height: 40rpx;
						border-radius: 4rpx;
						background-color: $brand-theme-color;
					}
				}

				/* 激活时 */
				.active {
					color: $text-font-color-1;
					background-color: #fff;
					font-weight: 600;
				}
			}

			/*右边商品内容*/
			.right {
				height: 100%;
				flex: 1;
				background-color: #fff;

				.scroll {
					height: 100%;
					scroll-behavior: smooth;

					/*右侧产品*/
					.productList {
						margin-bottom: 32rpx;
						color: $text-font-color-2;

						/*分类名*/
						.name {
							padding-left: 24rpx;
							height: 60rpx;
							line-height: 60rpx;
							font-weight: 800;
							color: $text-font-color-1;
							background-color: #fff;
						}

						/*产品内容*/
						.pro {
							display: flex;
							padding: 24rpx;
							height: 200rpx;
							width: 100%;

							/*左边封面图*/
							.left {
								margin-right: 16rpx;
								width: 160rpx;
								height: 160rpx;
								border-radius: 24rpx;
								overflow: hidden;
							}

							/*右边内容*/
							.right {
								display: flex;
								flex-direction: column;
								justify-content: space-between;

								/*商品名字*/
								.pro-name {
									font-weight: 600;
									@include textShenglue(1);
								}

								/*价格*/
								.price {
									display: flex;
									justify-content: start;
								}

								/*折扣和步进器*/
								.add-cart {
									display: flex;
									justify-content: space-between;

									// 折扣
									.discount {
										padding: 4rpx 16rpx;
										width: fit-content;
										height: fit-content;
										border: 1px solid $brand-ts-color;
										font-size: 24rpx;
										color: $brand-ts-color;
										text-align: center;
										border-radius: 8rpx;
									}

									/*步进器组件*/

									/*sku*/
									.sku {
										padding: 8rpx 12rpx;
										width: fit-content;
										height: fit-content;
										border-radius: 8rpx;
										background-color: $brand-theme-color;
										color: #fff;
										font-size: 24rpx;
									}
								}
							}
						}

						/* 选中最后一个 .pro 元素并设置高度为 100vh */
						&:last-child {
							height: calc(100vh - 84rpx);
						}
					}
				}
			}
		}

		/*规格面板*/
		.skuMenu {
			position: fixed;
			left: 0;
			bottom: 140rpx;
			display: flex;
			padding: 24rpx;
			width: 100%;
			background-color: #fff;

			.skuItem {
				padding: 8rpx 16rpx;
				margin-right: 16rpx;
				border: 1px solid $brand-theme-color;
				border-radius: 8rpx;
				font-size: 24rpx;
				color: $text-font-color-3;
			}

			.submit {
				padding: 8rpx 16rpx;
				border-radius: 8rpx;
				background-color: $brand-theme-color;
				color: #fff;
			}
		}

		/*底部*/
		.footer {
			display: flex;
			justify-content: space-between;
			position: fixed;
			left: 0;
			bottom: 0;
			padding: 24rpx;
			width: 100%;
			height: 140rpx;
			background-color: #fff;
			border-top: 1px solid $line-color-aux;
			z-index: 999;

			/*选好了*/
			.footer-left {
				display: flex;

				.cartIcon {
					position: relative;
					margin-right: 16rpx;
					padding: 16rpx;
					background-color: $card-bg-color;
					border-radius: 16rpx;
				}

				.total {
					display: flex;
				}
			}

			.ready {
				.btn {
					width: 200rpx;
					height: 70rpx;
					background-color: $brand-theme-color;
					color: #fff;
					border-radius: 80rpx;
					line-height: 70rpx;
					text-align: center;
				}
			}
		}

		/*底部弹窗*/
		.popup-content {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: fit-content;

			.codePic {
				padding: 24rpx;
				height: 400rpx;
				width: 400rpx;
				background-color: #fff;
				border-radius: 32rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.sava {
				margin-top: 32rpx;

				.btn {
					width: 600rpx;
					height: 80rpx;
					text-align: center;
					line-height: 80rpx;
					border-radius: 48rpx;
					background: linear-gradient(to right, #46b0fe, #35e4fe);
					color: #fff;
				}
			}
		}
	}
</style>